<template>
  <el-dialog v-model="visible" :title="'文件上传'" width="50%" :close-on-click-modal="false" append-to-body @closed="closeDialog">
    <div class="upload-file">
      <el-upload
        ref="fileUploadRef"
        multiple
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        v-model:file-list="fileList"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :show-file-list="true"
        :headers="headers"
        :auto-upload="false"
        v-if="!disabled"
        :data="extData"
      >
        <!-- 上传按钮 -->
        <template #trigger>
          <el-button type="primary">选取文件</el-button>
        </template>
        <template #tip v-if="showTip && !disabled">
          <div class="el-upload__tip">
            <span
              >大小不能超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>；</span
            >
            <span v-if="fileAccept"
              >允许上传的文件格式为 <b style="color: #f56c6c">{{ fileType.join(' , ') }}</b></span
            >
          </div>
        </template>
      </el-upload>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="false" type="success" icon="Upload" :disabled="fileList.length == 0" @click="fileUploadRef.submit()">上 传</el-button>
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes';
import { delOss, listByIds } from '@/api/system/oss';
import { globalHeaders } from '@/utils/request';

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: () => false
  },
  ossFileList: {
    type: [String, Object, Array],
    default: () => []
  },
  resourceIds: {
    type: [Array],
    default: () => []
  },
  typeFlag: propTypes.string.def('sys_default'),
  // 数量限制
  limit: propTypes.number.def(5),
  // 大小限制(MB)
  fileSize: propTypes.number.def(30),
  //文件类型, 例如 ['md', 'txt', 'pdf', 'zip', 'rar', '7z', 'mp4', 'mp3', 'wav', 'gif', 'png', 'jpg', 'jpeg', 'bmp', 'tif', 'tiff', 'svg', 'psd', 'ai', 'eps', 'cdr', 'sketch', 'ppt', 'pptx', 'xls', 'xlsx', 'doc', 'docx']
  fileType: propTypes.array.def([]),
  // 是否显示提示
  isShowTip: propTypes.bool.def(true),
  // 禁用组件（仅查看文件）
  disabled: propTypes.bool.def(false)
});
const visible = ref(props.modelValue);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['update:modelValue', 'close']);
const number = ref(0);
const uploadList = ref<any[]>([]);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + '/resource/oss/upload'); // 上传文件服务器地址
const headers = ref(globalHeaders());
const fileList = ref<any[]>([]);
const showTip = computed(() => props.isShowTip);

const extData = () => {
  return { resourceIds: props.resourceIds.join(','), typeFlag: props.typeFlag };
};

const fileUploadRef = ref<ElUploadInstance>();

// 监听 fileType 变化，更新 fileAccept
const fileAccept = computed(() => !!props.fileType.length);
// 监听visible 改变
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val) {
      reset();
    }
  }
);
const reset = () => {
  fileList.value = [];
  uploadList.value = [];
  number.value = 0;
};
watch(
  () => props.ossFileList,
  async (val) => {
    if (val) {
      let temp = 1;
      // 首先将值转为数组
      let list: any[] = [];
      if (Array.isArray(val)) {
        list = val;
      } else {
        const res = await listByIds(val);
        list = res.data.map((oss) => {
          return {
            name: oss.originalName,
            url: oss.url,
            ossId: oss.ossId
          };
        });
      }
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        item = { name: item.name, url: item.url, ossId: item.ossId };
        item.uid = item.uid || new Date().getTime() + temp++;
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  // 校检文件类型
  if (fileAccept.value) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
      return false;
    }
  }
  // 校检文件名是否包含特殊字符
  if (file.name.includes(',')) {
    proxy?.$modal.msgError('文件名不正确，不能包含英文逗号!');
    return false;
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy?.$modal.loading('正在上传文件，请稍候...');
  number.value++;
  return true;
};

// 文件个数超出
const handleExceed = () => {
  proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
};

// 上传失败
const handleUploadError = () => {
  proxy?.$modal.msgError('上传文件失败');
};

// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
  if (res.code === 200) {
    uploadList.value.push(res.data);
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgError(res.msg);
    fileUploadRef.value?.handleRemove(file);
    uploadedSuccessfully();
  }
};

// 上传结束处理
const uploadedSuccessfully = () => {
  if (number.value > 0 && uploadList.value.length === number.value) {
    // fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
    // uploadList.value = [];
    // number.value = 0;
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgSuccess('上传成功');
    closeDialog();
  }
};

const closeDialog = () => {
  if (visible.value) {
    emit('close', uploadList.value);
  }
  visible.value = false;
  emit('update:modelValue', false);
  reset();
};
</script>

<style lang="scss" scoped></style>
